package com.hudilao.filter;

import com.alibaba.fastjson.JSON;
import com.hudilao.common.BaseContext;
import com.hudilao.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;


import javax.servlet.*;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

//检查当前用户是否已经完成了登录--过滤器实现
//出于系统安全性考虑，我们要求用户未登录时不能访问系统内部-跳转到登录界面让用户登录
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter{
    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;


//        response.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1:8080");
//        response.setHeader("Access-Control-Allow-Credentials", "true");
//        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
//        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");


        //新增
        //HttpServletResponse response1 = (HttpServletResponse) response;
        //HttpServletRequest request1 = (HttpServletRequest) request;
//        response.setHeader("Access-Control-Allow-Origin", "*");
//        response.setHeader("Access-Control-Allow-Credentials", "true");
//        response.setHeader("Access-Control-Allow-Methods", "*");
//        response.setHeader("Access-Control-Allow-Headers", "Content-Type,Access-Token");
//        response.setHeader("Access-Control-Expose-Headers", "*");
//
//        if (request.getMethod().equals( RequestMethod.OPTIONS.toString())){
//            System.out.println("-----检查------");
//            return;
//        }
//        filterChain.doFilter(request, response);

        //1.获取本次请求的URI
        String requestURI = request.getRequestURI();
        log.info("拦截到请求：{}",requestURI);

        //2.判断本次请求是否需要处理
        //定义不需要处理的请求路径
        //放行页面：登录，登出，静态资源
        String[] urls = new String[]{
                "/user/user/login",
                "/employee/login",
                "/setmeal/**",
                "/employee/**",
                "/employee/register",
                "/stock/**",
                "/employee/**",
                "/dish/**",
                "/category/**",
                "/common/**",
                "/backend/**",
                "/front/**",
                "/static-resources/**",
                "/upload/**",
                "/favicon.ico",
                "/index/**",
                "/order/review/**",
                "/user/membership/list",
                "/user/membership/recharge",
                "/user/membership/decrease",
                "/user/order/count/status",
                "/user/order/page",
                "/user/order/status/submitted",
                "/user/order/status/paid",
                "/user/order/status/finished",
                "/user/order/status/reviewed",
                "/user/order/count/status",
                "/user/order/deliver",
                "/user/order/detail/**",
                "/review/order/em/**",
                "/user/orderDetail/sell"
//                "/user/order/**"
        };

        boolean check_result = check(urls,requestURI);

        //3.不用处理，直接放行
        if(check_result){
            log.info("本次请求{}不需要处理",requestURI);
            filterChain.doFilter(request,response);
            return;
        }

        //4、需要处理-判断登录状态。已登录，放行
        if(request.getSession().getAttribute("employee")!=null){
            log.info("用户已登录，用户id为：{}",request.getSession().getAttribute("employee"));

            //获取当前线程id
            long threadId = Thread.currentThread().getId();
            log.info("线程id{}",threadId);

            //可以在这里设置id通过threadLocal传递，属于同一个线程
            Long empId = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);

            filterChain.doFilter(request,response);
            return;
        }


        //4.2判断微信用户登录状态
        if(request.getSession().getAttribute("customer") != null){

            log.info("用户已登录，用户id为：{}",request.getSession().getAttribute("customer"));

            Long customerId = (Long) request.getSession().getAttribute("customer");
            BaseContext.setCurrentId(customerId);

            filterChain.doFilter(request,response);
            return;
        }

        //5、未登录，返回结果
        //通过输出流的方式向客户端页面响应数据
        log.info("用户未登录");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;

        //log.info("拦截到请求:{}",request.getRequestURI());
        //filterChain.doFilter(request,response);
    }

    //路径匹配，检查本次请求是否需要放行
    public boolean check(String[]urls,String requestURI){
        for(String url:urls){
            boolean match = PATH_MATCHER.match(url,requestURI);
            if(match){
                return true;
            }
        }
        return false;
    }



}
